/*
 * 
 * LegendShop 多用户商城系统
 * 
 *  版权所有,并保留所有权利。
 * 
 */
package com.legendshop.oa.controller;

import com.alibaba.fastjson.JSONObject;
import com.legendshop.dao.support.PageSupport;
import com.legendshop.framework.controller.BaseController;
import com.legendshop.oa.constants.DataSortResult;
import com.legendshop.oa.constants.PathResolver;
import com.legendshop.oa.constants.ProjectStatusEnum;
import com.legendshop.oa.dto.ProjectQueryDto;
import com.legendshop.oa.model.KeyValueEntity;
import com.legendshop.oa.model.Project;
import com.legendshop.oa.pages.AdminTilesPage;
import com.legendshop.oa.pages.BackPage;
import com.legendshop.oa.pages.RedirectPage;
import com.legendshop.oa.security.UserDetail;
import com.legendshop.oa.security.UserManager;
import com.legendshop.oa.service.ProjectService;
import com.legendshop.oa.util.CommonServiceWebUtil;
import com.legendshop.oa.util.PageSupportHelper;
import com.legendshop.util.AppUtils;
import com.legendshop.util.Arith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

/**
 * The Class ProjectController
 * 控制器
 */
@Controller
@RequestMapping("/admin/project")
public class ProjectController extends BaseController{
    @Autowired
    private ProjectService projectService;

	/**
	 * 列表查询
	 * TODO 只能看公开的和给登录用户授权的项目
	 */
    @RequestMapping("/query")
    public String query(HttpServletRequest request, HttpServletResponse response, ProjectQueryDto projectQueryDto) {
		DataSortResult sortResult = CommonServiceWebUtil.isDataSortByExternal(request, new String[] {"p1.id","p1.type","p1.name", "p1.start_time", "p1.end_time", "p1.workday" ,
				"p1.estimate_hours", "p1.actual_hours", "p1.principalRealName", "p1.testerRealName","p1.status"});
    	UserDetail userDetail = UserManager.getUser(request);
    	projectQueryDto.setUserDetail(userDetail);
    	projectQueryDto.setSortResult(sortResult);
        PageSupport<Project> ps = projectService.getProject(projectQueryDto);
        PageSupportHelper.savePage(request, ps);
        request.setAttribute("projectQueryDto", projectQueryDto);
        
		Double estimateHours = 0d; //预计工时
		Double actualHours = 0d;//实际工时
		if(AppUtils.isNotBlank(ps.getResultList())){
			for (Project project : ps.getResultList()) {
				
				if(project.getEstimateHours() != null){
					estimateHours = Arith.add(estimateHours, project.getEstimateHours());
				}
				
				if(project.getActualHours() != null){
					actualHours = Arith.add(actualHours, project.getActualHours());
				}
			}
		}
		
		request.setAttribute("estimateHours", estimateHours);
		
		request.setAttribute("actualHours", actualHours);

		request.setAttribute("now", new Date());
        
        return PathResolver.getPath(request, response, AdminTilesPage.PROJECT_LIST_PAGE);
    }
    
	/**
	 * 列表已经完成的项目
	 * TODO 只能看公开的和给登录用户授权的项目
	 */
    @RequestMapping("/queryFinish")
    public String queryFinish(HttpServletRequest request, HttpServletResponse response, ProjectQueryDto projectQueryDto) {
    	DataSortResult sortResult = CommonServiceWebUtil.isDataSortByExternal(request, new String[] {"p1.id", "p1.start_time", "p1.end_time", "p1.workday" ,
				"p1.estimate_hours", "p1.actual_hours", "p1.principalRealName", "p1.testerRealName","p1.status"});
    	UserDetail userDetail = UserManager.getUser(request);
    	projectQueryDto.setUserDetail(userDetail);
    	projectQueryDto.setSortResult(sortResult);
    	projectQueryDto.setStatus(ProjectStatusEnum.FINISH.value());
        PageSupport<Project> ps = projectService.getProject(projectQueryDto);
        PageSupportHelper.savePage(request, ps);
        request.setAttribute("projectQueryDto", projectQueryDto);
        
        
		Double estimateHours = 0d; //预计工时
		Double actualHours = 0d;//实际工时
		if(AppUtils.isNotBlank(ps.getResultList())){
			for (Project project : ps.getResultList()) {
				
				if(project.getEstimateHours() != null){
					estimateHours = Arith.add(estimateHours, project.getEstimateHours());
				}
				
				if(project.getActualHours() != null){
					actualHours = Arith.add(actualHours, project.getActualHours());
				}
			}
		}
		
		request.setAttribute("estimateHours", estimateHours);
		
		request.setAttribute("actualHours", actualHours);
        
        return PathResolver.getPath(request, response, AdminTilesPage.PROJECT_FINISH_LIST_PAGE);
    }

	/**
	 * 保存
	 */
    @RequestMapping(value = "/save")
    public String save(HttpServletRequest request, HttpServletResponse response, Project project) {
    	UserDetail ud = UserManager.getUser(request);
        projectService.saveProject(project,ud);
        saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("operation.successful"));
        if(ProjectStatusEnum.FINISH.value().equals(project.getStatus())) {
        	 return PathResolver.getPath(request, response, RedirectPage.PROJECT_FINISH_LIST_QUERY);
        }else{
        	 return PathResolver.getPath(request, response, RedirectPage.PROJECT_LIST_QUERY);
        }
       
    }

	/**
	 * 删除
	 */
    @RequestMapping(value = "/delete/{id}")
    public String delete(HttpServletRequest request, HttpServletResponse response, @PathVariable
    Long id) {
    	UserDetail userDetail = UserManager.getUser(request);
        Project project = projectService.getProject(userDetail, id);
        if(project != null) {
    		projectService.deleteProject(userDetail, project);
            saveMessage(request, ResourceBundle.getBundle("i18n/ApplicationResources").getString("entity.deleted"));
        }
        if(project.getStatus().equals(ProjectStatusEnum.FINISH.value())) {
       	 return PathResolver.getPath(request, response, RedirectPage.PROJECT_FINISH_LIST_QUERY);
       }else{
       	 return PathResolver.getPath(request, response, RedirectPage.PROJECT_LIST_QUERY);
       }
    }

	/**
	 * 根据Id加载
	 */
    @RequestMapping(value = "/load/{id}")
    public String load(HttpServletRequest request, HttpServletResponse response, @PathVariable
    Long id) {
    	UserDetail userDetail = UserManager.getUser(request);
        Project project = projectService.getProject(userDetail,id);
        request.setAttribute("project", project);
        return PathResolver.getPath(request, response, AdminTilesPage.PROJECT_EDIT_PAGE);
    }
    
   /**
	 * 加载编辑页面
	 */
	@RequestMapping(value = "/load")
	public String load(HttpServletRequest request, HttpServletResponse response) {
		return PathResolver.getPath(request, response, AdminTilesPage.PROJECT_EDIT_PAGE);
	}

   /**
	 * 更新编辑页面
	 */
    @RequestMapping(value = "/update")
    public String update(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
    	UserDetail userDetail = UserManager.getUser(request);
        Project project = projectService.getProject(userDetail, id);
		request.setAttribute("project", project);
		return PathResolver.getPath(request, response, BackPage.PROJECT_EDIT_PAGE);
    }
    
	/**
	 * 加载有效的项目
	 */
	@RequestMapping("/common/loadProjects")
	public @ResponseBody
	List<KeyValueEntity> loadProjectsEntity(HttpServletRequest request, HttpServletResponse response) {
		UserDetail userDetail = UserManager.getUser(request);
		return projectService.loadProjectsEntity(userDetail);
	}
	
	/**
	 * 加载自己的有效的项目
	 */
	@RequestMapping("/common/loadMyProjects")
	public @ResponseBody
	List<KeyValueEntity> loadMyProjectsEntity(HttpServletRequest request, HttpServletResponse response) {
		UserDetail userDetail = UserManager.getUser(request);
		return projectService.loadMyProjectsEntity(userDetail);
	}
	
	
	/**
	 * 加载自己的有效的项目
	 */
	@RequestMapping("/common/loadMyProjectEntities")
	public @ResponseBody
	JSONObject loadMyProjectEntities(HttpServletRequest request, HttpServletResponse response, String q, Integer pageSize, Integer currPage) {
		if (AppUtils.isBlank(pageSize)) {
			pageSize = 200;
		}
		if (AppUtils.isBlank(currPage) || currPage <= 0) {
			currPage = 1;
		}
		UserDetail userDetail = UserManager.getUser(request);
		return  projectService.loadMyProjectEntities(userDetail.getUsername(), q, pageSize, currPage);
	}

	/**
	 * 加载有效的项目模块
	 */
	@RequestMapping("/common/loadModules/{projectId}")
	public @ResponseBody
	List<KeyValueEntity> loadModulesEntity(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer projectId) {
		return projectService.loadModulesEntity(projectId);
	}

	/**
	 * 加载有效的项目模块
	 */
	@RequestMapping("/common/loadPlans/{projectId}")
	public @ResponseBody
	List<KeyValueEntity> loadPlansEntity(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer projectId) {
		return projectService.loadPlansEntity(projectId);
	}

}
